import json
import re

from django.contrib.auth.models import User
from django.http import JsonResponse
# from django.shortcuts import render
from blog.models import Blog, Report, Comment, Like, Collect

# Create your views here.
from usermanage.models import UserInfo


class BlogManage:
    @staticmethod
    def createBlog(request):
        # 判断用户是否提交数据
        if request.method == "POST":
            if not request.user.is_authenticated:
                return JsonResponse({
                    "status": 6,
                    "massage": "请先登录"
                })
            data = json.loads(request.body)
            type = data.get("type")
            # user = User.objects.get(id=request.user)
            # userinfo = UserInfo.objects.get(user=user)
            blog = Blog.objects.create(userID=request.user)
            blog.type = type
            blog.save()
            # 完成后返回到文章列表
            return JsonResponse({
                "status": 0,
                "message": "创建帖子成功",
                "blogid": blog.id
            })
        # 如果用户请求获取数据
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 删除帖子
    def deleteBlog(request):
        # 判断用户是否提交数据
        if request.method == "POST":
            if not request.user.is_authenticated:
                return JsonResponse({
                    "status": 6,
                    "massage": "请先登录"
                })
            data = json.loads(request.body)
            blogid = data.get("blogid")
            userinfo = UserInfo.objects.get(user=request.user)
            # try:
            blog = Blog.objects.filter(userID=request.user, id=blogid)
            # except:
            if not blog.exists():
                # 不存在这样的帖子
                return JsonResponse({
                    "status": 3,
                    "message": "不存在该帖子",
                    "blogid": blogid,
                    "userid": userinfo.user_id
                })
            blog.delete()
            return JsonResponse({
                "status": 0,
                "message": "已删除该帖子",
                "blogid": blogid,
                "userid": userinfo.user_id
            })
        # 如果用户请求获取数据
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 修改帖子
    def editBlog(request):
        if request.method == "POST":
            if not request.user.is_authenticated:
                return JsonResponse({
                    "status": 6,
                    "massage": "请先登录"
                })
            data = json.loads(request.body)
            blogid = data.get("id")
            title = data.get("title")
            # content = data.get("textcontent")
            text = data.get("text")
            type = data.get("type")
            if blogid is not None:
                # try:
                blog = Blog.objects.filter(id=blogid, userID=request.user)
                if blog.exists():
                    blog = Blog.objects.get(id=blogid, userID=request.user)
                    blog.title = title
                    blog.blogText = text
                    # blog.creatTime
                    # blog.htmlcontent = htmlcontent
                    blog.type = type
                    blog.save()
                    return JsonResponse({
                        "status": 0,
                        "message": "帖子修改成功"
                    })
                else:
                    return JsonResponse({
                        "status": 4,
                        "message": "帖子不存在或没有编辑权限"
                    })
            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数不全"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 获取帖子详情
    def getBlogInfo(request):
        if request.method == "POST":
            if not request.user.is_authenticated:
                return JsonResponse({
                    "status": 6,
                    "massage": "请先登录"
                })
            data = json.loads(request.body)
            blogid = data.get("id")
            op = data.get("op")
            if blogid is not None:
                blog = Blog.objects.get(id=blogid)
                if op == 1:
                    blog.readNum = blog.readNum + 1
                blog.save(update_fields=['readNum'])
                comments = Comment.objects.filter(commented_id=blogid).order_by("-commentTime")
                # print(9)
                # print(blogid)
                json_commentlist = []
                for comment in comments:
                    # 获取用户信息
                    commentUserInfo = UserInfo.objects.get(user=comment.commenter)
                    # if userprofile.avatar and hasattr(userprofile.avatar, 'url'):
                    #     avatar = prefix + str(userprofile.avatar.url)
                    # else:
                    #     avatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                    # avatar = userprofile.avatar
                    json_dict = {}
                    json_dict["user_id"] = commentUserInfo.user.id
                    json_dict["comment_id"] = comment.id
                    json_dict["realname"] = commentUserInfo.realname
                    json_dict["nickname"] = commentUserInfo.nickname
                    # json_dict["img"] = avatar
                    json_dict["text"] = comment.body
                    # json_dict["htmlcontent"] = "<p>" + comment.body + "</p>"
                    json_commentlist.append(json_dict)
                blog.commentNum = len(json_commentlist)
                blog.save()
                commentUserInfo = UserInfo.objects.get(user_id=request.user.id)
                if Like.objects.filter(likeUserID=commentUserInfo, beLikedBlog_id=blogid).exists():
                    is_like = 0
                else:
                    is_like = 1
                if Collect.objects.filter(collector=commentUserInfo, collectBlog_id=blogid).exists():
                    is_collect = 0
                else:
                    is_collect = 1
                return JsonResponse({
                    "status": 0,
                    "message": "帖子详情查看成功",
                    "data": {
                        "title": str(blog.blogTitle),
                        "textcontent": str(blog.blogText),
                        # "htmlcontent": blog.htmlcontent,
                        "type": blog.type,
                        "date": blog.creatTime,
                        "readnum": blog.readNum,
                        "commentnum": blog.commentNum,
                        "likeNum": blog.likeNum,
                        "is_like": is_like,
                        "is_collect": is_collect,
                        "commentlist": json_commentlist
                    }
                })

            else:
                return JsonResponse({
                    "status": 2,
                    "message": "参数错误"
                })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 获取用户所有帖子信息
    def getAllBlogs(request):
        if request.method == "POST":
            data = json.loads(request.body)
            userid = data.get('id')
            if userid is None:
                userid = request.user.id
            user = User.objects.get(id=userid)
            curUser = UserInfo.objects.get(user_id=userid)
            blogs = Blog.objects.filter(userID=user).order_by("-creatTime")
            json_list = []
            for blog in blogs:
                if blog.blogTitle == "":
                    continue
                is_like = 0
                curUser = UserInfo.objects.get(user_id=request.user.id)
                if Like.objects.filter(likeUserID=curUser, beLikedBlog=blog.id).exists():
                    is_like = 1
                else:
                    is_like = 0
                if Collect.objects.filter(collector=curUser, collectBlog=blog).exists():
                    is_collect = 1
                else:
                    is_collect = 0
                json_dict = {}
                json_dict["blogid"] = blog.id
                json_dict["title"] = blog.blogTitle
                # json_dict["textcontent"] = blog.content
                json_dict["text"] = blog.blogText
                json_dict["type"] = blog.type
                # json_dict["htmlcontent"] = blog.htmlcontent
                json_dict["date"] = blog.creatTime
                json_dict["readnum"] = blog.readNum
                json_dict["likeNum"] = blog.likeNum
                json_dict["commentNum"] = blog.commentNum
                json_dict["is_like"] = is_like
                json_dict["is_collect"] = is_collect
                json_list.append(json_dict)
            return JsonResponse({
                "status": 0,
                "data": {
                    "list": json_list
                }
            }, safe=False)
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 点赞/取消点赞
    def setBlogLike(request):
        if request.method == "POST":
            data = json.loads(request.body)
            blogid = data.get("id")
            like = data.get("type")  # 0 点赞，1取消点赞
            blog = Blog.objects.get(id=blogid)
            if not blog:
                return JsonResponse({
                    "status": 3,
                    "message": "不存在该作者或者该帖子"
                })
            if like == 0:
                blog.is_like = 0
                blog.save()
                curUser = UserInfo.objects.get(user_id=request.user.id)
                likes = Like.objects.filter(likeUserID=curUser, liked_id=blogid)
                for like in likes:
                    like.delete()
                    blog.likeNum = blog.likeNum - 1
                    blog.is_like = 1
                    blog.save()
                return JsonResponse({
                    "status": 0,
                    "message": "取消点赞成功"
                })
            else:
                blog.is_like = 1
                blog.save()
                curUser = UserInfo.objects.get(user_id=request.user.id)
                if Like.objects.filter(likeUserID=curUser, beLikedBlog=blog):
                    blog.is_like = 1
                    blog.save()
                    return JsonResponse({
                        "status": 5,
                        "message": "已经点赞过了"
                    })
                else:
                    curUser = UserInfo.objects.get(user_id=request.user.id)
                    like = Like.objects.create(likeUserID=curUser, beLikedBlog=blog)
                    like.save()
                    blog.likeNum = blog.likeNum + 1
                    blog.is_like = 0
                    blog.save()
                    return JsonResponse({
                        "status": 0,
                        "message": "点赞成功",
                    })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 收藏/取消收藏
    def setBlogCollect(request):
        if request.method == "POST":
            if not request.user.is_authenticated:
                return JsonResponse({
                    "status": 6,
                    "massage": "请先登录"
                })
            data = json.loads(request.body)
            blogid = data.get("id")
            collect = data.get("type")  # 0收藏，1 取消收藏
            blog = UserInfo.objects.get(id=blogid)
            if not blog:
                return JsonResponse({
                    "status": 3,
                    "message": "不存在该作者或者该帖子"
                })
            if collect == 0:  # 取消收藏
                profile = UserInfo.objects.get(user_id=request.user.id)
                collects = Collect.objects.filter(collector=profile, collectBlog_id=blogid)
                for collect in collects:
                    collect.delete()
                    blog.is_collect = 0
                    blog.save()
                return JsonResponse({
                    "status": 0,
                    "message": "取消收藏成功"
                })
            else:
                profile = UserInfo.objects.get(user_id=request.user.id)
                if Collect.objects.filter(collector=profile, collectBlog_id=blogid):
                    return JsonResponse({
                        "status": 5,
                        "message": "已经收藏过了"
                    })
                else:
                    profile = UserInfo.objects.get(user_id=request.user.id)
                    collect = Collect.objects.create(collector=profile, collectBlog_id=blogid)
                    collect.save()
                    blog.is_collect = 1
                    blog.save()

                    # # 生成消息通知并保存
                    # starmessage = Starmessage.objects.create(user_id=request.user.id, blog_id=blog.id,
                    #                                          to_user_id=blog.user.user.id)
                    # # commentmessage.message = comment_body
                    # starmessage.save()

                    return JsonResponse({
                        "status": 0,
                        "message": "收藏成功",
                    })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    # @staticmethod
    # 获取热门帖子信息列表
    # def getHotBlogs(request):
    #     if request.method == "POST":
    #         data = json.loads(request.body)
    #         type = data.get("type")
    #         if type == 0:
    #             blogs = Blog.objects.order_by("-readNum")
    #         else:
    #             blogs = Blog.objects.filter(type=type).order_by("-readNum")
    #         print(blogs)
    #         json_list = []
    #         for blog in blogs:
    #             json_dict = {}
    #             curUser = blog.user
    #             # if profile.avatar and hasattr(profile.avatar, 'url'):
    #             #     avatar = prefix + str(profile.avatar.url)
    #             # else:
    #             #     avatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
    #             # avatar = curUser.avatar
    #             json_dict['blogname'] = blog.title
    #             # json_dict['avatar'] = avatar
    #             json_dict['readnum'] = blog.readnum
    #             json_dict['likenum'] = blog.likenum
    #             json_dict['commentnum'] = blog.commentNum
    #             json_dict['userid'] = blog.user.user_id
    #             json_dict['text'] = blog.blogText
    #             # json_dict['textcontent'] = blog.content
    #             # json_dict['htmlcontent'] = blog.htmlcontent
    #             json_dict['blogid'] = blog.id
    #             user = UserInfo.objects.get(id=curUser.user_id)
    #             json_dict['username'] = user.username
    #             json_list.append(json_dict)
    #         return JsonResponse({
    #             "status": 0,
    #             "data": {
    #                 "list": json_list
    #             }
    #         }, safe=False)
    #     else:
    #         return JsonResponse({
    #             "status": 1,
    #             "message": "error method"
    #         })

    @staticmethod
    # 搜索帖子
    def search_blog(request):
        if request.method == "POST":
            data = json.loads(request.body)
            text = data.get("text")
            type = data.get("type")
            if type == 0:
                blogs = Blog.objects.all().order_by("-creatTime")
            else:
                blogs = Blog.objects.filter(type=type).order_by("-creatTime")
            json_list = []
            for blog in blogs:
                if re.search(text, blog.blogTitle):
                    json_dict = {}
                    user = blog.userID
                    json_dict['blogname'] = str(blog.blogTitle)
                    json_dict['blogid'] = blog.id
                    json_dict['blogText'] = str(blog.blogText)
                    # json_dict['htmlcontent'] = blog.htmlcontent
                    json_dict['date'] = blog.creatTime
                    json_dict['type'] = blog.type
                    json_dict['username'] = str(user.username)
                    json_dict['userid'] = user.id
                    json_dict['readnum'] = blog.readNum
                    json_dict['likenum'] = blog.likeNum
                    json_dict['commentNum'] = blog.commentNum
                    json_list.append(json_dict)
            return JsonResponse({
                "status": 0,
                "data": {
                    "list": json_list
                }
            }, safe=False)
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 列出收藏帖子列表
    def get_collect_blog_list(request):
        if request.method == 'POST':
            data = json.loads(request.body)
            userid = data.get('userid')
            type = data.get('type')
            if type == 0 and request.user.is_authenticated:
                userid = request.user.id
            curUser = UserInfo.objects.get(user_id=userid)
            collects = Collect.objects.filter(collector=curUser)
            json_list = []
            for collect in collects:
                blogid = collect.collectBlog_id
                blog = Blog.objects.get(id=blogid)
                json_dict = {}
                json_dict["blogid"] = blogid
                json_dict["title"] = blog.blogTitle
                json_dict["text"] = blog.blogText
                json_dict["create"] = blog.creatTime
                user = blog.userID
                json_dict["author"] = user.username
                json_dict["userid"] = user.id
                json_dict["intro"] = curUser.intro
                # if Collect.objects.filter(collector_id=userid, collectBlog_id=blogid):
                #     json_dict["is_collect"] = 0
                # else:
                #     json_dict["is_collect"] = 1
                json_list.append(json_dict)
            return JsonResponse({
                "status": 0,
                "data": {
                    "list": json_list
                }
            })
        else:
            return JsonResponse({
                "status": 1,
                "message": "error method"
            })

    @staticmethod
    # 发表评论
    def post_comment(request):
        if request.user.is_authenticated:
            # 处理 POST 请求
            if request.method == 'POST':
                data = json.loads(request.body)
                blog_id = data.get('blogid')
                comment_text = data.get('text')
                visibility = data.get('vis')
                # 尝试评论
                # 创建新的评论对象
                curUser = request.user
                curUserInfo = UserInfo.objects.get(user=curUser)
                comment = Comment.objects.create(commenter=curUser, commented_id=blog_id)
                comment.commentText = comment_text
                # 保存后提交
                comment.save()
                blog = Blog.objects.get(id=blog_id)
                # print(blog_id)
                blog.commentNum = blog.commentNum + 1
                blog.save(update_fields=['commentNum'])
                # print(blog.tipnum)

                # # 生成消息通知并保存
                # print(blog.user.id)
                # commentmessage = Commentmessage.objects.create(user_id=request.user.id, blog_id=blog_id,
                #                                                to_user_id=blog.user.user.id)
                # # commentmessage.message = comment_body
                # commentmessage.save()

                # 获取用户信息
                # user_id = int(request.user.id)
                # userprofile = UserInfo.objects.get(user_id=user_id)
                # if userprofile.avatar and hasattr(userprofile.avatar, 'url'):
                #     avatar = prefix + str(userprofile.avatar.url)
                # else:
                #     avatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                # avatar = profile.avatar
                return JsonResponse({
                    "status": 0,
                    "comment_id": comment.id,
                    "userid": request.user.id,
                })
            # 处理错误请求
            else:
                return JsonResponse({
                    "status": 1,
                    "message": "请使用post请求"
                })

        else:
            return JsonResponse({
                "status": 6,
                "message": "请登录后再评论"
            })

    @staticmethod
    # 获取评论
    def get_comment(request):
        # 处理 POST 请求
        if request.method == 'POST':
            data = json.loads(request.body)
            blog_id = data.get('blogid')
            curUser = UserInfo.objects.get(user_id=request.user.id)
            comments = Comment.objects.filter(commented_id=blog_id)
            blog_obj = Blog.objects.get(id=blog_id)
            comment_list = []
            for comment in comments:
                comment_dic = {}
                commenter = comment.commenter
                comment_dic['commentid'] = comment.id
                comment_dic['commenter'] = commenter.id
                comment_dic['commenttext'] = comment.commentText
                comment_dic['visibility'] = comment.visibility
                comment_list.append(comment_dic)
            return JsonResponse({
                "status": 0,
                "data": {
                    "comment_list": comment_list
                }
            })
        # 处理错误请求
        else:
            return JsonResponse({
                "status": 1,
                "message": "请使用post请求"
            })


class CreateReport:
    @staticmethod
    def create_report(request):
        if request.user.is_authenticated:
            # 处理 POST 请求
            if request.method == 'POST':
                data = json.loads(request.body)
                ''' type:1用户2评论3博客 '''
                type = data.get('type')
                blog_id = data.get('blogid')
                comment_id = data.get('commentid')
                user_id = data.get('userid')
                # 尝试举报
                # 创建新的举报对象
                report = Report.objects.create(user_id=request.user.id)
                report.reason = data.get('reason')
                report.reportType = type
                if type == 1:
                    report.reportedUserID = user_id
                elif type == 2:
                    report.reportedCommentID = comment_id
                elif type == 3:
                    report.reportedBlogID = blog_id
                else:
                    return JsonResponse({
                        "status": 2,
                        "message": "参数错误"
                    })
                report.save()

                # # 生成消息通知并保存
                # blog = Blogs.objects.get(id=blog_id)
                # reportmessage = Report.objects.create(blog=blog.id,
                #                                              to_user_id=blog.user.user.id)
                # # commentmessage.message = comment_body
                # reportmessage.type = 2
                # reportmessage.save()

                return JsonResponse({
                    "status": 0,
                    "message": "举报成功"
                })
            # 处理错误请求
            else:
                return JsonResponse({
                    "status": 1,
                    "message": "请使用post请求"
                })

        else:
            return JsonResponse({
                "status": 6,
                "message": "请登录后再举报"
            })

    @staticmethod
    def get_report(request):
        if request.user.is_authenticated:
            # 处理 POST 请求
            if request.method == 'POST':
                data = json.loads(request.body)
                handled = data.get('handled')
                type = data.get('type')
                reports = Report.objects.filter(reportType=type, handled=handled)
                if reports.count() == 0:
                    return JsonResponse({
                        "status": 5,
                        "message": "没有对应的记录"
                    })
                json_list = []
                for report in reports:
                    json_dict = {}
                    if type == 1:
                        reporteduser = User.objects.get(id=report.reportedUserID)
                    elif type == 2:
                        comment = Comment.objects.get(id=report.reportedCommentID)
                        reporteduser = comment.commenter
                        json_dict["comment_id"] = report.reportedCommentID
                        json_dict["text"] = comment.commentText
                    elif type == 3:
                        blog = Blog.objects.get(id=report.reportedBlogID)
                        reporteduser = blog.userID
                        json_dict["blog_id"] = report.reportedBlogID
                        json_dict["title"] = Blog.objects.get(id=report.reportedBlogID).blogTitle
                        json_dict["text"] = Blog.objects.get(id=report.reportedBlogID).blogText
                    else:
                        return JsonResponse({
                            "status": 2,
                            "message": "参数错误"
                        })
                    reporteruser = report.user
                    json_dict["report_id"] = report.id
                    json_dict["type"] = report.reportType
                    json_dict["reason"] = report.reason
                    json_dict["handled"] = report.handled
                    json_dict["reportuserid"] = reporteruser.id
                    json_dict["reporteduserid"] = reporteduser.id
                    json_dict["reportedusername"] = reporteduser.username
                    json_dict["time"] = report.reportTime
                    json_list.append(json_dict)
                return JsonResponse({
                    "status": 0,
                    "data": {
                        "reported_list": json_list
                    }
                })
            # 处理错误请求
            else:
                return JsonResponse({
                    "status": 1,
                    "message": "请使用post请求"
                })

        else:
            return JsonResponse({
                "status": 6,
                "message": "请先登录"
            })

    @staticmethod
    # 处理帖子举报
    def handle_report(request):
        if request.user.is_authenticated:
            # 处理 POST 请求
            if request.method == 'POST':
                data = json.loads(request.body)
                type = data.get('type')
                handle_result = data.get('result')
                report_id = data.get('id')
                report = Report.objects.get(id=report_id)
                if handle_result not in [0, 1]:
                    return JsonResponse({
                        "status": 2,
                        "message": "参数错误"
                    })
                if type == 1:
                    reporteduser = User.objects.get(id=report.reportedUserID)
                    relatedreports = Report.objects.filter(reportedUserID=reporteduser.id)
                    for relatedreport in relatedreports:
                        relatedreport.handled = True
                    if handle_result == 1:
                        reporteduser.is_active = False
                    return JsonResponse({
                        "status": 0,
                        "message": "处理成功"
                    })

                elif type == 2:
                    comment = Comment.objects.get(id=report.reportedCommentID)
                    relatedreports = Report.objects.filter(reportedCommentID=comment.id)
                    for relatedreport in relatedreports:
                        relatedreport.handled = True
                    if handle_result == 1:
                        comment.visibility = False
                    return JsonResponse({
                        "status": 0,
                        "message": "处理成功"
                    })
                elif type == 3:
                    blog = Blog.objects.get(id=report.reportedBlogID)
                    if handle_result == 1:
                        comments = Comment.objects.filter(commented=blog)
                        for comment in comments:
                            comment.visibility = False

                        relatedreports = Report.objects.filter(reportedBlogID=blog.id)
                        for relatedreport in relatedreports:
                            relatedreport.delete()

                        blog.visibility = False
                        return JsonResponse({
                            "status": 0,
                            "message": "删除成功"
                        })
                    reports = Report.objects.filter(reportedBlogID=report.blog_id)
                    for report in reports:
                        report.handled = True
                    return JsonResponse({
                        "status": 0,
                        "message": "操作成功"
                    })
                else:
                    return JsonResponse({
                        "status": 2,
                        "message": "参数错误"
                    })
            # 处理错误请求
            else:
                return JsonResponse({
                    "status": 1,
                    "message": "请使用post请求"
                })
        else:
            return JsonResponse({
                "status": 6,
                "message": "请先登录"
            })
